package com.bodacn.packapp.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.bodacn.packapp.DBUtil;
import com.bodacn.packapp.DataUtils;
import com.bodacn.packapp.R;
import com.bodacn.packapp.SearchPOBean;
import com.bodacn.packapp.SharedPreferenceUtils;
import com.bodacn.packapp.adapter.SearchPOAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

public class SearchPoActivity extends AppCompatActivity {

    @BindView(R.id.iv_on_package_back)
    ImageView ivOnPackageBack;
    @BindView(R.id.tv_on_package_back)
    TextView tvOnPackageBack;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.tv_change)
    TextView tvChange;
    @BindView(R.id.tv_remove)
    TextView tvRemove;
    @BindView(R.id.tv_cancle_remove)
    TextView tvCancleRemove;
    @BindView(R.id.cb_contain_box)
    CheckBox cbContainBox;
    @BindView(R.id.cb_contain_remove)
    CheckBox cbContainRemove;
    @BindView(R.id.tv_order)
    TextView tvOrder;
    @BindView(R.id.tv_goods)
    TextView tvGoods;
    @BindView(R.id.tv_PO)
    TextView tvPO;
    @BindView(R.id.tv_yzjs)
    TextView tvYzjs;
    @BindView(R.id.tv_yzxs)
    TextView tvYzxs;
    @BindView(R.id.tv_yzymxs)
    TextView tvYzymxs;
    @BindView(R.id.tv_yzwmxs)
    TextView tvYzwmxs;
    @BindView(R.id.tv_wzxs)
    TextView tvWzxs;
    @BindView(R.id.tv_xzjs)
    TextView tvXzjs;
    @BindView(R.id.lv)
    ListView lv;
    private String UserNo = "", EndBoxCheck = "", EliminateCheck = "",PO="";
    private final int MSG_GETLIST = 8001;
    private final int MSG_DELETE = 8002;
    private final int MSG_CHANGE = 8003;
    private final int MSG_REMOVE = 8004;
    private final int MSG_Error = 8008;
    private JSONArray listJsonarray, deleteJsonarray;
    private SearchPOAdapter searchPOAdapter;
    private List<SearchPOBean> searchPOBeanList = new ArrayList<>();
    public SharedPreferences sharedPreferences;
    SearchPOBean searchPOBean;
    List<String> POList = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_po);
        sharedPreferences = getSharedPreferences("boda", MODE_PRIVATE);
        ButterKnife.bind(this);
        UserNo = getIntent().getStringExtra("curLoginUserNo");
        searchPOAdapter = new SearchPOAdapter(this, searchPOBeanList);
        lv.setAdapter(searchPOAdapter);


        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (searchPOBeanList.get(position).isCheck()) {
                    searchPOBeanList.get(position).setCheck(false);
                    if (POList != null && POList.size() > 0) {
                        for (int i = 0; i < POList.size(); i++) {
                            if (POList.contains(searchPOBeanList.get(position).getPoh())) {
                                POList.remove(searchPOBeanList.get(position).getPoh());
                            }

                        }
                    }
                } else {
                    searchPOBeanList.get(position).setCheck(true);
                    if (POList != null && POList.size() > 0) {
                        if (!POList.contains(searchPOBeanList.get(position).getPoh())) {
                            POList.add(searchPOBeanList.get(position).getPoh());
                        }
                    } else {
                        POList.add(searchPOBeanList.get(position).getPoh());

                    }

                }
                searchPOAdapter.notifyDataSetChanged();
            }
        });

        cbContainRemove.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    SharedPreferenceUtils.putData(sharedPreferences, "EliminateCheck", "1");
                } else {
                    SharedPreferenceUtils.putData(sharedPreferences, "EliminateCheck", "0");
                }
            }
        });
        cbContainBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    SharedPreferenceUtils.putData(sharedPreferences, "EndBoxCheck", "1");
                } else {
                    SharedPreferenceUtils.putData(sharedPreferences, "EndBoxCheck", "0");
                }
            }
        });
        if (SharedPreferenceUtils.getData(sharedPreferences, "EndBoxCheck", "0").equals("1")) {
            cbContainBox.setChecked(true);
        } else {
            cbContainBox.setChecked(false);
        }
        if (SharedPreferenceUtils.getData(sharedPreferences, "EliminateCheck", "0").equals("1")) {
            cbContainRemove.setChecked(true);
        } else {
            cbContainRemove.setChecked(false);
        }
        search("SelectPoList", MSG_GETLIST);
    }

    @OnClick({R.id.iv_on_package_back, R.id.tv_on_package_back, R.id.tv_search, R.id.tv_change, R.id.tv_remove, R.id.tv_cancle_remove})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_on_package_back:
            case R.id.tv_on_package_back:
                finish();
                break;
            case R.id.tv_search:
                search("SelectPoList", MSG_GETLIST);
                break;
            //切换
            case R.id.tv_change:
                if (POList!=null&&POList.size()>0){
                    if (POList.size()==1){
                        for (int i = 0; i <searchPOBeanList.size() ; i++) {
                            if (searchPOBeanList.get(i).isCheck()){
                                searchPOBean=searchPOBeanList.get(i);
                                break;
                            }
                        }
                        EventBus.getDefault().post(new BackInfo("",searchPOBean.getPoh(), searchPOBean.getHh(), searchPOBean.getHyh(), "PO"));
                        finish();
                    }else {
                        Toast.makeText(SearchPoActivity.this, "选择1行进行切换", Toast.LENGTH_SHORT).show();

                    }
                }else {
                    Toast.makeText(SearchPoActivity.this, "选择切换的行", Toast.LENGTH_SHORT).show();
                }
                break;
            //剔除
            case R.id.tv_remove:
                if (POList!=null&&POList.size()>0){
                    PO= DataUtils.listToString(POList);
                    search("EliminatePoList", MSG_REMOVE);
                }else {
                    Toast.makeText(SearchPoActivity.this, "选择剔除的行", Toast.LENGTH_SHORT).show();
                }
                break;
            //取消剔除
            case R.id.tv_cancle_remove:
                if (POList!=null&&POList.size()>0){
                    PO= DataUtils.listToString(POList);
                    search("CancleEliminatePoList", MSG_REMOVE);
                }else {
                    Toast.makeText(SearchPoActivity.this, "选择取消剔除的行", Toast.LENGTH_SHORT).show();

                }
                break;
        }
    }

    private void search(String OperType, int msg) {
        if (cbContainBox.isChecked()) {
            EndBoxCheck = "1";
        } else {
            EndBoxCheck = "0";
        }
        if (cbContainRemove.isChecked()) {
            EliminateCheck = "1";
        } else {
            EliminateCheck = "0";
        }
        String sqlFindcJname = "EXEC KeyPoint_Pack_MidGetPOList @OperType='" + OperType + "',@UserNo='" + UserNo
                + "',@EndBoxCheck='" + EndBoxCheck + "',@EliminateCheck='" + EliminateCheck + "',@PO='" + PO + "'";
        ReadSQLData(sqlFindcJname, msg);
    }


    private void ReadSQLData(String sql, int type) {
        System.out.print("----存储过程:" + sql);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    JSONArray jsonArray = DBUtil.QuerySQL2JSON(sql);
                    System.out.print("----返回结果：" + jsonArray);
                    System.out.print("----过程：" + sql);
                    Message msg = new Message();
                    String OperType = "";
                    //往界面转数据;
                    if ((jsonArray != null) && (jsonArray.length() > 0)) {
                        if (jsonArray.optJSONObject(0).has("OperType"))
                            OperType = jsonArray.optJSONObject(0).getString("OperType");
                        if (jsonArray.optJSONObject(0).has("OPERTYPE"))
                            OperType = jsonArray.optJSONObject(0).getString("OPERTYPE");
                        if (OperType.length() > 0) {
                            //获取列表
                            if (OperType.equals("SelectPoList")) {
                                listJsonarray = jsonArray;
                                msg.what = type;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                            }
                            //剔除
                            if (OperType.equals("EliminatePoList") || OperType.equals("CancleEliminatePoList")) {
                                deleteJsonarray = jsonArray;
                                msg.what = type;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                            }
                            //切换
                            if (OperType.equals("ScanBarcode")) {
                                deleteJsonarray = jsonArray;
                                msg.what = type;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                            }
                        }
                        if (jsonArray.optJSONObject(0).has("SQLExcept") == true) {
                            //刷新界面;
                            Message errmsg = new Message();
                            Bundle bundle = new Bundle();
                            bundle.putString("HintInfo", jsonArray.optJSONObject(0).getString("SQLMessage"));
                            errmsg.what = MSG_Error;
                            errmsg.setData(bundle);
                            handler.removeMessages(errmsg.what);
                            handler.sendMessage(errmsg);
                        }
                    } else {
                        //刷新界面;
                        Message errmsg = new Message();
                        Bundle bundle = new Bundle();
                        bundle.putString("HintInfo", "未返回任何数据!");
                        errmsg.what = type;
                        errmsg.setData(bundle);
                        handler.removeMessages(errmsg.what);
                        handler.sendMessage(errmsg);
                    }

                } catch (Exception e) {
                    Message msg = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putString("HintInfo", "未返回任何数据!");
                    msg.what = MSG_Error;
                    msg.setData(bundle);
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);
                }

            }

        };
        new Thread(run).start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            Bundle bundle;
            switch (msg.what) {
                //获取列表
                case MSG_GETLIST:
                    System.out.println("MSG_GETLIST");
                    if (listJsonarray != null && listJsonarray.length() > 0) {
                        try {
                            if (listJsonarray.getJSONObject(0).has("ResultInfo")) {
                                Toast.makeText(SearchPoActivity.this, listJsonarray.getJSONObject(0).getString("ResultInfo"), Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        List<SearchPOBean> seachPauseBeans = new Gson().fromJson(String.valueOf(listJsonarray), new TypeToken<List<SearchPOBean>>() {
                        }.getType());
                        searchPOBeanList.clear();
                        searchPOBeanList.addAll(seachPauseBeans);
                        searchPOAdapter.notifyDataSetChanged();
                    } else {
                        searchPOBeanList.clear();
                        searchPOAdapter.notifyDataSetChanged();
                    }
                    break;
                //剔除 取消剔除
                case MSG_REMOVE:
                    if (deleteJsonarray != null && deleteJsonarray.length() > 0) {
                        try {
                            if (deleteJsonarray.getJSONObject(0).has("ResultInfo")) {
                                Toast.makeText(SearchPoActivity.this, deleteJsonarray.getJSONObject(0).getString("ResultInfo"), Toast.LENGTH_SHORT).show();

                            }
                            if (deleteJsonarray.getJSONObject(0).has("EliminatePoList")) {
                                if (deleteJsonarray.getJSONObject(0).getString("EliminatePoList").equals("Y")) {
                                    POList.clear();
                                    PO = "";
                                    search("SelectPoList", MSG_GETLIST);
                                }
                            }
                            if (deleteJsonarray.getJSONObject(0).has("CancleEliminatePoList")) {
                                if (deleteJsonarray.getJSONObject(0).getString("CancleEliminatePoList").equals("Y")) {
                                    POList.clear();
                                    PO = "";
                                    search("SelectPoList", MSG_GETLIST);
                                }
                            }
                            if (deleteJsonarray.getJSONObject(0).has("GetPoList")) {
                                if (deleteJsonarray.getJSONObject(0).getString("GetPoList").equals("Y")) {
                                    PO = "";
                                    search("SelectPoList", MSG_GETLIST);
                                }
                            }
                            if (deleteJsonarray.getJSONObject(0).has("ErrInfo")) {
                                AlertDialog alertDialog = new AlertDialog.Builder(SearchPoActivity.this)
                                        .setTitle("系统提示").setMessage(deleteJsonarray.getJSONObject(0).getString("ResultInfo"))
                                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                                return;
                                            }
                                        }).create(); // 创建对话框
                                alertDialog.show(); // 显示对话框
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Toast.makeText(SearchPoActivity.this, "删除失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case MSG_Error:
                    bundle = msg.getData();
                    Toast.makeText(SearchPoActivity.this, bundle.getString("HintInfo"), Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };
}
